import tkinter as tk
from tkinter import scrolledtext, messagebox, PanedWindow

# 提取指定命令的十六进制数据
def extract_specific_command_data(text, command_name, header_value=None):
    lines = text.splitlines()
    extracted_data = []
    index = 0

    for line in lines:
        if line.strip().startswith(command_name):
            # 找到指定命令中的数据部分
            start_idx = line.find("(") + 1
            end_idx = line.find(");", start_idx)
            if end_idx == -1:
                continue

            params_str = line[start_idx:end_idx].strip()
            params = params_str.split(',')
            hex_data = [p.strip() for p in params if p.strip().startswith("0x")]

            if hex_data:
                # 按照要求格式化为数组定义
                if header_value is None:
                    header_value = 0x29  # 默认指令头为0x29

                array_name = f"cmd{index}"
                data_length = len(hex_data)
                array_content = [f"0x{header_value:02X}", f"0x{data_length:02X}"] + ["0x00"] + hex_data
                array_definition = f"static uint8_t {array_name}[] = {{{', '.join(array_content)}}};"
                extracted_data.append(array_definition)
                index += 1

    return extracted_data


# 将输入的十六进制数据转换为C语言数组格式
def convert_hex_to_array(hex_data):
    converted_data = []
    hex_list = hex_data.split()

    # 从遇到的11开始提取数据（包括11在内）
    start_index = None
    for i, hex_value in enumerate(hex_list):
        if hex_value == "11":
            start_index = i
            break

    if start_index is None:
        return ["未找到起始数据0X11"]

    # 提取从11开始的数据（最多128个）
    max_data_count = 128
    end_index = min(start_index + max_data_count, len(hex_list))
    data_to_convert = hex_list[start_index:end_index]

    # 格式化为C语言数组
    formatted_data = [f"0x{value}" for value in data_to_convert]

    # 将数据分成每行八个数据
    lines = [", ".join(formatted_data[i:i + 8]) for i in range(0, len(formatted_data), 8)]

    return lines


# 提取指定命令数据界面
def extract_gui():
    def extract_data():
        input_text = input_textbox.get("1.0", tk.END)
        command_name = command_entry.get().strip()
        header_value_str = header_entry.get().strip()

        if header_value_str.startswith("0x"):
            header_value = int(header_value_str, 16)
        else:
            header_value = None

        extracted_data = extract_specific_command_data(input_text, command_name, header_value)

        output_textbox.delete("1.0", tk.END)
        for data in extracted_data:
            output_textbox.insert(tk.END, data + "\n")

    extract_window = tk.Toplevel()
    extract_window.title("提取指定命令数据")

    # 输入框与标签
    input_label = tk.Label(extract_window, text="请粘贴要处理的命令文本:")
    input_label.pack()

    input_textbox = scrolledtext.ScrolledText(extract_window, width=60, height=10)
    input_textbox.pack()

    # 命令名称输入框与标签
    command_label = tk.Label(extract_window, text="请输入要提取的命令名称（例如：GEN_WR）: 留空则默认为GEN_WR")
    command_label.pack()

    command_entry = tk.Entry(extract_window)
    command_entry.pack()

    # 指令头输入框与标签
    header_label = tk.Label(extract_window, text="请输入指令头的十六进制数值（例如：0x29），留空则默认为0x29:")
    header_label.pack()

    header_entry = tk.Entry(extract_window)
    header_entry.pack()

    # 提取按钮
    extract_button = tk.Button(extract_window, text="提取数据", command=extract_data)
    extract_button.pack()

    # 输出框
    output_label = tk.Label(extract_window, text="提取结果:")
    output_label.pack()

    output_textbox = scrolledtext.ScrolledText(extract_window, width=60, height=10)
    output_textbox.pack()

# 十六进制数据转换界面
def convert_gui():
    def convert_data():
        hex_data = hex_textbox.get("1.0", tk.END)
        converted_data = convert_hex_to_array(hex_data)

        converted_textbox.delete("1.0", tk.END)
        for data in converted_data:
            converted_textbox.insert(tk.END, data + "\n")

    convert_window = tk.Toplevel()
    convert_window.title("PPS 十六进制数据转换为数组")

    # 输入框与标签
    hex_label = tk.Label(convert_window, text="请粘贴要转换的PPS 十六进制数据（每行以空格分隔）:")
    hex_label.pack()

    hex_textbox = scrolledtext.ScrolledText(convert_window, width=120, height=16)
    hex_textbox.pack()

    # 转换按钮
    convert_button = tk.Button(convert_window, text="转换数据", command=convert_data)
    convert_button.pack()

    # 输出框
    converted_label = tk.Label(convert_window, text="转换后的数据:")
    converted_label.pack()

    converted_textbox = scrolledtext.ScrolledText(convert_window, width=120, height=16)
    converted_textbox.pack()


# 创建主界面
def create_main_gui():
    root = tk.Tk()
    root.title("数据处理工具")

    # 提取指定命令数据按钮
    extract_button = tk.Button(root, text="提取指定命令数据", command=extract_gui)
    extract_button.pack(pady=20)

    # 十六进制数据转换按钮
    convert_button = tk.Button(root, text="PPS/十六进制数据转换为数组", command=convert_gui)
    convert_button.pack(pady=20)

    root.mainloop()


# 启动主界面
if __name__ == "__main__":
    create_main_gui()